package com.media.appmedia.base;

import java.util.ArrayList;
import java.util.Set;

import org.json.JSONException;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.media.appmedia.R;
import com.media.appmedia.contarl.FragmentTabAdapter;
import com.media.appmedia.entity.IsSignBean;
import com.media.appmedia.entity.LockADBean;
import com.media.appmedia.lock.LockScreenActivity;
import com.media.appmedia.lock.LockScreenService;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.thread.SaveImageThread;
import com.media.appmedia.thread.SaveImageThread.IsOk;
import com.media.appmedia.util.MethodUtils;
import com.media.appmedia.util.NetUtil;
import com.media.appmedia.util.PhoneInfoUtils;
import com.media.appmedia.util.ToastUtils;
import com.slidingmenu.lib.SlidingMenu;

/**
 * 
 * 作者: Rose 业务名: 功能说明: 用于自定义Application程序入口，方便更改业务逻辑 编写日期: 2014-11-27
 * 
 */
public class BaseApplication extends Application {
	private ArrayList<Activity> listAct = new ArrayList<Activity>();
	// 设置锁屏
	private boolean setLock;
	// 设置通知栏
	private boolean setNotfind;
	// 设置声音
	private boolean isSound;
	public static BaseApplication application;
	private SlidingMenu mSlidingMenu;
	private FragmentTabAdapter fragmentTabAdapter;
	private String userPhone;
	private String mobId;
	private UserInfo userInfo = UserInfo.getUserInfo();
	private int isSign = 0;

	// 锁屏数据专用
	private boolean isOk = false;
	private ArrayList<LockADBean> lockBeans;
	private DbUtils db;
	private int mType;
	private LockScreenActivity lockActivity;
	public boolean returnIsOk;

	

	public void finishLock() {
		if (lockActivity != null) {
			this.lockActivity.finish();
		}
	}

	public void setLockActivity(LockScreenActivity lockActivity) {
		this.lockActivity = lockActivity;
	}

	/**
	 * 
	 * 方法说明：根据设置判断用户是否需要推送通知栏
	 * 
	 */
	private void setIsJpush() {
		if (setNotfind) {
			JPushInterface.setAlias(this, "sgfc88", new TagAliasCallback() {

				@Override
				public void gotResult(int arg0, String arg1, Set<String> arg2) {

				}
			});
		} else {
			JPushInterface.setAlias(this, "", new TagAliasCallback() {

				@Override
				public void gotResult(int arg0, String arg1, Set<String> arg2) {

				}
			});
		}
	}

	public boolean isSound() {
		return isSound;
	}

	public void setSound(boolean isSound) {
		this.isSound = isSound;
	}

	public void setListAct(Activity activity) {
		listAct.add(activity);
	}

	public void backAct() {
		for (int i = 0; i < listAct.size(); i++) {
			listAct.get(i).finish();
		}
	}

	public boolean isSetLock() {
		return setLock;
	}

	public void setSetLock(boolean setLock) {
		this.setLock = setLock;
	}

	public boolean isSetNotfind() {
		return setNotfind;
	}

	public void setSetNotfind(boolean setNotfind) {
		this.setNotfind = setNotfind;
	}

	public int getIsSign() {
		return isSign;
	}

	public void setIsSign(int isSign) {
		this.isSign = isSign;
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public String getMobId() {
		return mobId;
	}

	public void setMobId(String mobId) {
		this.mobId = mobId;
	}

	public String getUserPhone() {
		return userPhone;
	}

	public void setUserPhone(String userPhone) {
		this.userPhone = userPhone;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		application = this;
		db = DbUtils.create(this);
		JPushInterface.init(this);
		getNetIsSign(PhoneInfoUtils.getIMEI(getApplicationContext()));
		setSetting();
		sendLock();
	}

	public static BaseApplication getApplication() {
		return application;
	}

	public SlidingMenu getmSlidingMenu() {
		return mSlidingMenu;
	}

	public void setmSlidingMenu(SlidingMenu mSlidingMenu) {
		this.mSlidingMenu = mSlidingMenu;
	}

	public FragmentTabAdapter getFragmentTabAdapter() {
		return fragmentTabAdapter;
	}

	public void setFragmentTabAdapter(FragmentTabAdapter fragmentTabAdapter) {
		this.fragmentTabAdapter = fragmentTabAdapter;
	}

	/**
	 * 
	 * 方法说明：获取当前用户的签到状态
	 * 
	 * @param biaozhifu
	 */
	private void getNetIsSign(String biaozhifu) {
		ProtocolService.getIsSign(biaozhifu, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				IsSignBean bean = JSONObject.parseObject(arg0.result,
						IsSignBean.class);
				if (bean.getMessage() == 1) {
					isSign = bean.getSign_record();
				}
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				ToastUtils.show(getApplicationContext(),
						R.string.phone_verify_send_fail);
			}
		});
	}

	/**
	 * 
	 * 方法说明：得到用户存储的设置！
	 * 
	 */
	public void setSetting() {
		setLock = MethodUtils.getSetting1(getApplication());
		setNotfind = MethodUtils.getSetting2(getApplication());
		isSound = MethodUtils.getSetting3(getApplication());
		setIsJpush();
	}

	/**
	 * 
	 * 方法说明：开启锁屏服务
	 * 
	 */
	public void startLockService() {
		if (setLock) {
			startService(new Intent(getApplicationContext(),
					LockScreenService.class)); // 这里要显示的调用服务
		}
	}

	/**
	 * 
	 * 方法说明：关闭锁屏服务
	 * 
	 */
	public void stopLockService() {
		// 关闭锁屏服务
		stopService(new Intent(getApplicationContext(), LockScreenService.class));
	}

	public boolean isOk() {
		return isOk;
	}

	public void setOk(boolean isOk) {
		this.isOk = isOk;
	}

	public ArrayList<LockADBean> getLockBeans() {
		try {
			return  (ArrayList<LockADBean>) db.findAll(LockADBean.class);
		} catch (DbException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void setLockBeans(ArrayList<LockADBean> lockBeans) {
		this.lockBeans = lockBeans;
	}

	/**
	 * 
	 * 方法说明：提供数据库操作的类
	 * 
	 * @return
	 */
	public DbUtils getDb() {
		return db;
	}

	public void delete(String imageId) {
		try {
			db.delete(LockADBean.class,
					WhereBuilder.b("lock_image_id", "==", imageId));
			takeLockBean();
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * 方法说明：是否需要下载新数据 Start
	 * 
	 */
	public boolean sendLock() {
		isOk = false;
		returnIsOk = false;
		if (!NetUtil.isNetConn(application)) {
			takeLockBean();
			if (lockBeans != null) {
				isOk = true;
			}
			return false;
		}
		ProtocolService.isCache(PhoneInfoUtils.getIMEI(application),
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							org.json.JSONObject obj = new org.json.JSONObject(
									arg0.result);
							int type = obj.getInt("message");
							mType = MethodUtils.getLockInfo(application);
							if (mType < type) {
								// 需要更新
								returnIsOk = true;
								mType = type;
								getLeftLockResult();
							} else {
								// 无需更新
								returnIsOk = false;
								takeLockBean();
								isOk = true;
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {

					}
				});
		return returnIsOk;
	}

	/**
	 * 
	 * 方法说明：获取解锁界面的广告数据源集合
	 * 
	 */
	private void getLeftLockResult() {
		ProtocolService.getLockLeft(
				PhoneInfoUtils.getIMEI(getApplicationContext()),
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							org.json.JSONObject obj = new org.json.JSONObject(
									arg0.result);
							if (obj.getInt("message") == 1) {
								lockBeans = (ArrayList<LockADBean>) JSONArray
										.parseArray(obj.getString("0"),
												LockADBean.class);
								ArrayList<String> imageUrls = new ArrayList<String>();

								for (int i = 0; i < lockBeans.size(); i++) {
									imageUrls.add(lockBeans.get(i)
											.getLock_image_photo());
								}
								new SaveImageThread(imageUrls, new IsOk() {

									@Override
									public void canGetOut() {
										isOk = true;
										MethodUtils.setLockInfo(
												getApplicationContext(), mType);
									}
								}).start();
								try {
									db.deleteAll(LockADBean.class);
									db.saveAll(lockBeans);
									stopLockService();
									startLockService();
								} catch (DbException e) {
									e.printStackTrace();
								}
							} else {
								isOk = true;
								return;
							}
						} catch (JSONException e1) {
							e1.printStackTrace();
						}

					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						System.out.println();
					}
				});
	}

	/**
	 * 
	 * 方法说明：取出数据库中缓存的Lock数据集
	 * 
	 */
	private void takeLockBean() {
		try {
			if (lockBeans != null) {
				lockBeans.removeAll(lockBeans);
			}
			lockBeans = (ArrayList<LockADBean>) db.findAll(LockADBean.class);
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

}
